package com.zzyl.nursing.service.impl;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;

import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;

/**
 * 老人家属Service业务层处理
 *
 * @author xulei
 * @date 2025-08-01
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired

    private TokenService tokenService;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "花开富贵",
            "锦上开花",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );



    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        String openId  = wechatService.getOpenid(dto.getCode());
        FamilyMember familyMember = familyMemberMapper.selectOne(Wrappers.lambdaQuery(FamilyMember.class)
                .eq(FamilyMember::getOpenId,openId));
        if(ObjectUtil.isEmpty(familyMember)){
            familyMember = FamilyMember.builder()
                    .openId(openId)
                    .build();
        }
        String phone = wechatService.getPhone(dto.getPhoneCode());
        if (ObjectUtil.notEqual(phone,familyMember.getPhone())){
            familyMember.setPhone(phone);
        }
        if (ObjectUtil.isNotEmpty(familyMember.getId())){
            updateById(familyMember);
            return null;
        }

        String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()) )
                + StringUtils.substring(familyMember.getPhone(),7);

        familyMember.setName(nickName);

        save(familyMember);

        Map<String,Object>claims = new HashMap<>();
        claims.put("userId",familyMember.getId());
        claims.put("userName",familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo vo = new LoginVo();
        vo.setToken(token);
        vo.setNickName(familyMember.getName());
        return vo;
    }





}
